<template>
    <div>
        <Modal v-model="modal.officeFlag"
               :loading="loading"
               @on-ok="ok"
               title="office导入题库"
               @on-cancel="cancel">
            <Upload
                    multiple
                    type="drag"
                    paste
                    :data="{'courseId':courseId}"
                    :headers="Authorization"
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
                            application/vnd.openxmlformats-officedocument.wordprocessingml.document,
                            application/msword,application/vnd.ms-powerpoint,application/vnd.ms-excel"
                    :before-upload="beforeupload"
                    :format="['docx','doc','xls','xlsx']"
                    :on-format-error="handleFormatError"
                    :on-success="handerSuccess"
                    action="/api/backstage/qB/questionBankImport">
                <div style="padding: 20px">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>文档（可批量批量上传，按住Ctrl键在点击上传文件可进行批量选着，也可在文件夹批量选中然后拖拽在框内）</p>
                </div>
            </Upload>
        </Modal>
        <topic-preview :topicPreviewModal="topicPreviewModal"></topic-preview>
    </div>
</template>

<script>
    import jscookie from "js-cookie";
    import topicPreview from "@c/questionBank/topicPreview"

    export default {
        props: {
            modal: {
                officeFlag: false,
            }
        },
        data() {
            return {
                Authorization: {AuthorizationNotes: null},
                loading: true,
                courseId: null,
                topicPreviewModal: {
                    topicPreviewFlag: false,
                    subjectMap: new Map(),
                }
            }
        },
        methods: {
            ok() {
                this.topicPreviewModal.topicPreviewFlag = true
                this.$parent.modal.officeFlag = false
            },
            cancel() {
                this.$parent.modal.officeFlag = false
            },
            /**
             * 文件上传前配置请求头以及cookie信息
             */
            beforeupload() {
                let time = new Date();
                this.Authorization.AuthorizationNotes = time.getTime()
                let token = sessionStorage.getItem("token")
                jscookie.set("token", token)
                return true;
            },
            /**
             * 非法文件错误提示
             * @param file
             */
            handleFormatError(file) {
                this.$Notice.warning({
                    title: '文件类型出错',
                    desc: '只支持\'docx\',\'doc\',\'xls\',\'xlsx\''
                });
            },
            /**
             * 导入成功返回的对象
             * @param val
             */
            handerSuccess(val) {
                let questionTypeList = new Array("单选题", "多选题", "填空题", "判断题", "简答题", "论述题", "案例题", "选择题", "答案与解析");
                let questionTypeIndexOfAndName = questionTypeList.map(m => {
                    return {"name": m, "num": val.indexOf(m) - 2}
                }).filter(f => f.num != -3)
                let questionTypeIndexOf = questionTypeList.map(m => {
                    return val.indexOf(m) - 2
                }).filter(f => f != -3).sort()
                let map = new Map();
                for (let i = 0; i < questionTypeIndexOf.length; i++) {
                    if (i == questionTypeIndexOf.length - 1) {
                        let name = questionTypeIndexOfAndName.filter(f => f.num == questionTypeIndexOf[i]).map(m => {
                            return m.name
                        })[0]
                        map.set(name, val.substring(questionTypeIndexOf[i], val.length))
                        break
                    }
                    let name = questionTypeIndexOfAndName.filter(f => f.num == questionTypeIndexOf[i]).map(m => {
                        return m.name
                    })[0]
                    map.set(name, val.substring(questionTypeIndexOf[i], questionTypeIndexOf[i + 1]))
                }
                let re = /^[0-9]+.?[0-9]*$/;
                let abc = new Array("A", "B", "C", "D", "E", "F", "H", "I", "J", "K")
                let str = new Array("．", ".", "、", ",", "，")
                let multipleChoice = {}     //选着题对象
                let multipleChoiceFlag = false
                let multipleChoiceList = [] //选着题集合
                let trueOrFalse = {}        //判断题对象
                let trueOrFalseFlag = false
                let trueOrFalseList = []    //判断题集合
                let shortAnswer = {}        //简答题
                let shortAnswerFlag = false
                let shortAnswerList = []    //简答题结合
                let essayQuestions = {}     //论述题
                let essayQuestionsFlag = false;
                let essayQuestionsList = [] //论述题
                let caseQuestion = {}       //案例题
                let caseQuestionList = []   //案例题集合
                let caseQuestionFlag = false
                let caseQuestionTopic = {}
                let caseQuestionOption = []
                let defaultFlag = true
                let currentLineNum = 0
                map.forEach((item, name) => {
                    item.split(/\n/g).filter(f => f.trim().length > 0).forEach((m, indexs) => {
                        let titleFlag = re.test(m.trim().split("")[0]) && (str.includes(m.trim().split("")[1]) || str.includes(m.trim().split("")[2]));
                        switch (name) {
                            case "选择题":
                                if (!m.includes(name)) {
                                    //判断是不是题目：当前列的第一位是不是数字，下一个的第一个是不是字母A
                                    if (titleFlag && item.split(/\n/g).filter(f => f.trim().length > 0)[indexs + 1].split("").includes("A")) {
                                        if (!(JSON.stringify(multipleChoice) == "{}")) {
                                            multipleChoiceList.push(multipleChoice)
                                        }
                                        multipleChoice = {}
                                        multipleChoice.subType = 1
                                        multipleChoice.subTitle = m.trim()
                                        multipleChoice.options = []
                                        multipleChoice.subAnswer = null
                                        multipleChoice.subAnsweranalysis = null
                                        multipleChoice.remarks = ["无"]
                                        multipleChoice.courseId = null
                                    } else if (abc.includes(m.trim().split("")[0])) {
                                        multipleChoice.options.push({"optionInfo": m.trim()})
                                    } else {
                                        multipleChoice.remarks.push(m.trim())
                                    }
                                }
                                break;
                            case "多选题":

                                break;
                            case "填空题":

                                break;
                            case "判断题":
                                if (!m.includes(name)) {
                                    if (titleFlag) {
                                        if (!(JSON.stringify(trueOrFalse) == "{}")) {
                                            trueOrFalseList.push(trueOrFalse)
                                        }
                                        trueOrFalse = {}
                                        trueOrFalse.subType =4
                                        trueOrFalse.subTitle = m.trim()
                                        trueOrFalse.subAnswer = null
                                        trueOrFalse.subAnsweranalysis = null
                                        trueOrFalse.remarks = ["无"]
                                        trueOrFalse.courseId = null
                                    } else {
                                        trueOrFalse.remarks.push(m.trim())
                                    }
                                }
                                break;
                            case "简答题":
                                if (!m.includes(name)) {
                                    if (titleFlag) {
                                        if (!(JSON.stringify(shortAnswer) == "{}")) {
                                            shortAnswerList.push(shortAnswer)
                                        }
                                        shortAnswer = {}
                                        shortAnswer.subType = 5
                                        shortAnswer.subTitle = m.trim()
                                        shortAnswer.subAnswer = null
                                        shortAnswer.subAnsweranalysis = null
                                        shortAnswer.courseId = null
                                    } else {
                                        shortAnswer.subAnswer = shortAnswer.subAnswer != null ? shortAnswer.subAnswer : "" + m.trim()
                                    }
                                }
                                break;
                            case "论述题":
                                if (!m.includes(name)) {
                                    if (titleFlag) {
                                        if (!(JSON.stringify(essayQuestions) == "{}")) {
                                            essayQuestionsList.push(essayQuestions)
                                        }
                                        essayQuestions = {}
                                        essayQuestions.subType = 6
                                        essayQuestions.subTitle = m.trim()
                                        essayQuestions.subAnswer = null
                                        essayQuestions.subAnsweranalysis = null
                                        essayQuestions.courseId = null
                                    } else {
                                        essayQuestions.subAnswer = essayQuestions.subAnswer != null ? essayQuestions.subAnswer : '' + m.trim()
                                    }
                                }
                                break;
                            case "案例题":
                                if (!m.includes(name)) {
                                    if (titleFlag) {
                                        caseQuestionFlag = true
                                        caseQuestion = {}
                                        caseQuestion.subType = 7
                                        caseQuestion.remarks = ["无"]
                                        caseQuestion.subTitle = ""
                                        caseQuestion.courseId = null
                                        caseQuestion.articleChildrenSubtitle = []
                                    }
                                    if (caseQuestionFlag) {
                                        caseQuestion.subTitle = caseQuestion.subTitle + m.trim()
                                        let array = item.split(/\n/g).filter(f => f.trim().length > 0)[indexs + 1]
                                        if (array.trim().split("")[0] == "(" && re.test(array.trim().split("")[1])) {
                                            caseQuestionList.push(caseQuestion)
                                            caseQuestionFlag = false
                                        }
                                    } else if (m.trim().split("")[0] == "(" && re.test(m.trim().split("")[1])) {
                                        caseQuestionTopic = {}
                                        caseQuestionTopic.subTitle = m.trim()
                                        caseQuestion.articleChildrenSubtitle.push(caseQuestionTopic)
                                        let array = item.split(/\n/g).filter(f => f.trim().length > 0)[indexs + 1]
                                        array != undefined && array.trim().split("")[0] == "A" ? caseQuestion.articleChildrenSubtitle[caseQuestion.articleChildrenSubtitle.length - 1].options = [] : ""
                                    } else if (abc.includes(m.trim().split("")[0])) {
                                        caseQuestion.articleChildrenSubtitle[caseQuestion.articleChildrenSubtitle.length - 1].options.push({"optionInfo": m.trim()})
                                    } else {
                                        caseQuestion.remarks.push({"remarks": m.trim()})
                                    }
                                }
                                break;
                            default:
                                if (defaultFlag) {
                                    multipleChoiceList.push(multipleChoice)
                                    trueOrFalseList.push(trueOrFalse)
                                    shortAnswerList.push(shortAnswer)
                                    essayQuestionsList.push(essayQuestions)
                                    defaultFlag = false
                                }
                                if (m.includes("单选题")) {
                                    multipleChoiceFlag = true
                                }
                                if (m.includes("判断题")) {
                                    trueOrFalseFlag = true
                                    multipleChoiceFlag = false
                                }
                                if (m.includes("简答题")) {
                                    shortAnswerFlag = true
                                    trueOrFalseFlag = false
                                    multipleChoiceFlag = false
                                }
                                if(m.includes("论述题")){
                                    essayQuestionsFlag = true
                                    shortAnswerFlag = false
                                    trueOrFalseFlag = false
                                    multipleChoiceFlag = false
                                }
                                let sNum = m.trim().substring(0, 2)
                                if (str.includes(sNum.split("")[1])) {
                                    sNum = sNum.substring(0, 1)
                                }
                                let isNum = true
                                let nextrow = item.split(/\n/g).filter(f => f.trim().length > 0)[indexs + 1]
                                //判断下一行是不是数字
                                isNum = re.test(nextrow!=undefined?nextrow.trim().substring(0, 2):'')
                                if (!isNum  && nextrow!==undefined  && questionTypeList.filter(f=>nextrow.includes(f)).length==0) {
                                    currentLineNum = re.test(sNum)?sNum:currentLineNum
                                }
                               //判断当前行开始是不是数字
                                if (!re.test(sNum) && nextrow!=undefined && questionTypeList.filter(f=>nextrow.includes(f)).length==0) {
                                    sNum = currentLineNum
                                }
                                if (multipleChoiceFlag) {
                                    multipleChoiceList.forEach(mindex => {
                                        let fNum = mindex.subTitle.substring(0, 2)
                                        let interceptSubscript = re.test(sNum)?3:0
                                        if (str.includes(fNum.split("")[1])) {
                                            fNum = fNum.substring(0, 1)
                                            interceptSubscript = re.test(sNum)?2:0
                                        }
                                        if (sNum == fNum) {
                                            if (m.trim().includes('【')) {
                                                mindex.subAnswer =  m.trim().substring(interceptSubscript, m.trim().indexOf("【"))
                                                mindex.subAnsweranalysis = (mindex.subAnsweranalysis!=null?mindex.subAnsweranalysis:"") + m.trim().substring(m.trim().indexOf("】") + 1, m.trim().length)
                                            } else {
                                                mindex.subAnswer = m.trim().substring(interceptSubscript, m.trim().length)
                                            }
                                        }
                                    })
                                } else if (trueOrFalseFlag) {
                                    trueOrFalseList.forEach(mindex => {
                                        let fNum = mindex.subTitle.substring(0, 2)
                                        let interceptSubscript = re.test(sNum)?3:0
                                        if (str.includes(fNum.split("")[1])) {
                                            fNum = fNum.substring(0, 1)
                                            interceptSubscript = re.test(sNum)?2:0
                                        }
                                        if (sNum == fNum) {
                                            if (m.trim().includes('【解析】')) {
                                                mindex.subAnswer =  m.trim().substring(interceptSubscript, m.trim().indexOf("【"))
                                                mindex.subAnsweranalysis = (mindex.subAnsweranalysis!=null?mindex.subAnsweranalysis:"") + m.trim().substring(m.trim().indexOf("】") + 1, m.trim().length)
                                            } else {
                                                mindex.subAnswer = m.trim().substring(interceptSubscript, m.trim().length)
                                            }
                                        }
                                    })
                                } else if (shortAnswerFlag) {
                                    shortAnswerList.forEach(mindex => {
                                        let fNum = mindex.subTitle.substring(0, 2)
                                        let interceptSubscript = re.test(sNum)?3:0
                                        if (str.includes(fNum.split("")[1])) {
                                            fNum = fNum.substring(0, 1)
                                            interceptSubscript = re.test(sNum)?2:0
                                        }
                                        if (sNum == fNum) {
                                            if (m.trim().includes('【解析】')) {
                                                mindex.subAnswer = (mindex.subAnswer!=null?mindex.subAnswer:'') + m.trim().substring(interceptSubscript, m.trim().indexOf("【"))
                                                mindex.subAnsweranalysis = (mindex.subAnsweranalysis!=null?mindex.subAnsweranalysis:'') + m.trim().substring(m.trim().indexOf("】") + 1, m.trim().length)
                                            } else {
                                                mindex.subAnswer = (mindex.subAnswer!=null?mindex.subAnswer:'') + m.trim().substring(interceptSubscript, m.trim().length)
                                            }
                                        }
                                    })
                                }else if (essayQuestionsFlag){
                                    essayQuestionsList.forEach(mindex => {
                                        let fNum = mindex.subTitle.substring(0, 2)
                                        let interceptSubscript = re.test(sNum)?3:0
                                        if (str.includes(fNum.split("")[1])) {
                                            fNum = fNum.substring(0, 1)
                                            interceptSubscript = re.test(sNum)?2:0
                                        }
                                        if (sNum == fNum) {
                                            if (m.trim().includes('【解析】')) {
                                                mindex.subAnswer = (mindex.subAnswer!=null?mindex.subAnswer:'') + m.trim().substring(interceptSubscript, m.trim().indexOf("【"))
                                                mindex.subAnsweranalysis = (mindex.subAnsweranalysis!=null?mindex.subAnsweranalysis:'') + m.trim().substring(m.trim().indexOf("】") + 1, m.trim().length)
                                            } else {
                                                mindex.subAnswer = (mindex.subAnswer!=null?mindex.subAnswer:'') + m.trim().substring(interceptSubscript, m.trim().length)
                                            }
                                        }
                                    })
                                }
                                break;
                        }
                    })
                })
                this.topicPreviewModal.subjectMap.set("选着题", multipleChoiceList)
                this.topicPreviewModal.subjectMap.set("判断题", trueOrFalseList)
                this.topicPreviewModal.subjectMap.set("简答题", shortAnswerList)
                this.topicPreviewModal.subjectMap.set("论述题", essayQuestionsList)
                this.topicPreviewModal.subjectMap.set("案例题", caseQuestionList)
            }
        },

        watch: {
            'modal.officeFlag'(val) {
                if (val) {

                }
            }
        },
        components: {topicPreview}
    }
</script>

<style scoped>

</style>